package com.cloud.mkz.core.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cloud.mkz.admin.api.dto.AuthedUser;
import com.cloud.mkz.admin.api.entity.RbacMenu;
import com.cloud.mkz.core.common.constant.CacheConstants;
import com.cloud.mkz.core.common.constant.SecurityConstants;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.cloud.mkz.core.common.utils.RedisUtil;

import cn.hutool.core.util.StrUtil;

import java.util.List;

public class BaseController<T> implements ApplicationContextAware {
	@Autowired
	protected HttpServletRequest request = null;
	@Autowired
	protected HttpServletResponse response = null;
	@Autowired
	protected RedisUtil redisUtil;
	protected ApplicationContext applicationContext = null;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	//获取用户信息实体
	private AuthedUser getUserinfo(){
		String tokenStr = getAuthToken();
		if(StrUtil.isBlank(tokenStr)){
			return null;
		}
		Object userObject = redisUtil.get(CacheConstants.PROJECT_OAUTH_TOKEN + tokenStr);
		if(userObject==null||StrUtil.isEmpty(userObject.toString())){
			return null;
		}
		AuthedUser logUser = (AuthedUser)userObject;
		if(null==logUser||null==logUser.getUserId()){
			return null;
		}
		return logUser;
	}
	//获取当前用户Token
	public String getAuthToken(){
		HttpSession session = ((HttpServletRequest) request).getSession();
		if(session==null) {
			return null;
		}
		Object tokenStr = session.getAttribute(SecurityConstants.SESSION_X_OUTH_TOKEN);
		if(tokenStr==null||StrUtil.isEmpty(tokenStr.toString())){
			return null;
		}
		return tokenStr.toString();
	}
	//获取登陆用户的菜单树
	public List<RbacMenu> getMenuTree(){ return getUserinfo().getMenuTree(); }
	//获取登陆用户的主键
	public Long getUserId(){
		return getUserinfo().getUserId();
	}
	//获取登陆用户的登陆名
	public String getUserName(){
		return getUserinfo().getUserName();
	}
	//获取登陆用户的姓名
	public String getFullName(){
		return getUserinfo().getFullName();
	}
	//获取登陆用户的部门主键
	public Long getDeptId(){
		return getUserinfo().getDeptId();
	}
	//获取登陆用户的单位主键
	public Long getOrgId(){
		return getUserinfo().getOrgId();
	}
}
